//
//  CellStatusViewModel.swift
//  weibobbaj
//
//  Created by Tiffany宝 on 16/4/21.
//  Copyright © 2016年 Tiffany. All rights reserved.

// StatusCell

import UIKit
import SDWebImage
import YYText
import SVProgressHUD

class CellStatusViewModel: NSObject {
    
    var status: StatusModel?{
        
        
        didSet{
            
            dealMemberImg()
            dealSource()
            // 设置转发微博的内容
            if let s = status?.retweeted_status {
                // @昵称:内容
                if let name = s.user?.name, content = s.text {
                    retweetText = "@\(name)~\(content)"
                    retweetAttributedString = self.attributedText(retweetText!)
                }
            }
            
            retweetPicViewSize = calRetweetPicViewSize(status?.retweeted_status?.pic_urls)
            originalPicViewSize = calRetweetPicViewSize(status?.pic_urls)
            //            dealCreatAtText()
            
            // status?.created_at 系统传过来的时间
            createDate = self.sinaDate(status?.created_at)
            
            //            self.attributedText(status?.text ?? "")
            originalAttributedString = self.attributedText(status?.text ?? "")
        }
        
    }
    
    //转发微博的文字
    var retweetText: String?
    
    //来自的文字
    var sourceText: String?
    
    //转发微博配图的视图大小
    var retweetPicViewSize: CGSize = CGSizeZero
    
    //微博正文配图的大小
    var originalPicViewSize: CGSize = CGSizeZero
    
    //原创微博的富文本内容
    var originalAttributedString: NSAttributedString?
    
    //转发微博的富文本内容
    var retweetAttributedString: NSAttributedString?
    
    //MARK - 处理首页微博图片表情 & 特殊字符高亮
    func attributedText(text: String) -> NSAttributedString{
        
        //原生的富文本
        let attributeString = NSMutableAttributedString(string: text)
        
        var results = [XHMatchResult]()
        
        //1.匹配出表情字符串
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u2E80-\\u9FFF]+\\]") { (count, captureString, captureRange, _) -> Void in
            
            print("\(captureString.memory)----\(captureRange.memory)")
            let result = XHMatchResult(captureString: captureString.memory! , range: captureRange.memory)
            results.append(result)
        }
        
        
        //为了防止越界异常,所以我们倒着遍历
        for value in results.reverse(){
            //2.通过表情字符串找到表情模型
            if let emotion = EmotionKeyboardViewModel.sharViewModel.emotionWithChs(value.captureString as String){
                
                print(emotion)
                //3.再通过表情模型生成表情图片的富文本,并且把对应位置的表情文字给替换掉
                let image = UIImage(named: "\(emotion.folderName ?? "")/\(emotion.png ?? "")", inBundle: EmotionKeyboardViewModel.sharViewModel.loadBundle(), compatibleWithTraitCollection: nil)
                
                //初始化文字附件
                let font = UIFont.systemFontOfSize(StatusCellContentFontSize)
                
                let attr = NSMutableAttributedString.yy_attachmentStringWithContent(image, contentMode: UIViewContentMode.ScaleAspectFill, attachmentSize: CGSize(width: font.lineHeight, height: font.lineHeight), alignToFont: font, alignment: YYTextVerticalAlignment.Center)
                
                //初始化文字附件
//                let attachment = XHTextAttachment()
//                attachment.image = image
//                let font = UIFont.systemFontOfSize(StatusCellContentFontSize)
//                //设置文字附件的大小
//                attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
//                
//                //初始化一个富文本
//                let attr = NSAttributedString(attachment: attachment)
                
                //并且把对应位置的表情文字给替换掉
                attributeString.replaceCharactersInRange(value.range, withAttributedString: attr)
            }
            
        }
        
        //设置字体
        //        attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: NSMakeRange(0, attributeString.length))
        
        // 添加特殊字符文字颜色
        // 话题
        addLinkColor("#[^#]+#", attributeString: attributeString)
        // @
        addLinkColor("@[\\u4e00-\\u9fa5A-Za-z0-9_\\-]+", attributeString: attributeString)
        // url
        addLinkColor("([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?", attributeString: attributeString)
        
        // 添加字体大小
        attributeString.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(StatusCellContentFontSize), range: NSMakeRange(0, attributeString.length))
        
        return attributeString
    }
    
    /// 添加特殊字符的颜色
    func addLinkColor(regex: String, attributeString: NSMutableAttributedString){
        
        // 话题？？ #asdfa#
        (attributeString.string as NSString).enumerateStringsMatchedByRegex(regex) { (_, captureString, captureRange, _) -> Void in
            print(captureString.memory)
            attributeString.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 80/255, green: 125/255, blue: 175/255, alpha: 1), range: captureRange.memory)
            
            
            //        YYTextBorder *border = [YYTextBorder borderWithFillColor:[UIColor grayColor] cornerRadius:3];
            //
            //            YYTextHighlight *highlight = [YYTextHighlight new];
            //            [highlight setColor:[UIColor whiteColor]];
            //            [highlight setBackgroundBorder:highlightBorder];
            //            highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
            //                NSLog(@"tap text range:...");
            //                // 你也可以把事件回调放到 YYLabel 和 YYTextView 来处理。
            //            };
            //
            //            // 2. 把"高亮"属性设置到某个文本范围
            //            [attributedText yy_setTextHighlight:highlight range:highlightRange];
            
            // 1. 初始化一个背景对象
            let border = YYTextBorder(fillColor: UIColor(red: 177/255, green: 215/255, blue: 255/255, alpha: 1), cornerRadius: 3)
            // 边框的边距
            border.insets = UIEdgeInsetsZero
            
            
            // 2. 初始化高亮对象
            let highlight = YYTextHighlight()
            // 设置高亮的时候的文字颜色
            highlight.setColor(UIColor(red: 80/255, green: 125/255, blue: 175/255, alpha: 1))
            // 设置高亮时的背景
            highlight.setBackgroundBorder(border)
            let s = (captureString.memory)! as String
            // void(^YYTextAction)(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect);
            highlight.tapAction = { (containerView: UIView, text: NSAttributedString, range: NSRange, rect: CGRect)->() in
                print("特殊字符点击了")
                SVProgressHUD.showInfoWithStatus(s)
            }
            // 3. 将高亮对象添加到attributedString里面
            attributeString.yy_setTextHighlight(highlight, range: captureRange.memory)
        }
    }
    
    //距离当前时间的微博创建的时间(xx分钟之前)
    var creatAtText: String?{
        
        return self.dealCreatAtText(createDate ?? NSDate())
    }
    
    var createDate: NSDate?
    
    override var description: String{
        
        let keys = ["status"]
        
        //模型转字典
        return dictionaryWithValuesForKeys(keys).description
    }
    
    //把系统时间的String传进来,转换成NSDate,只执行一次
    private func sinaDate(createAt: String?) -> NSDate?{
        
        //获取时间字符串
        guard let timeStr = createAt else{
            
            return nil
        }
        // 2015-08-10 10:10:10 yyyy-MM-dd HH:mm:ss
        //转换成NSDate
        //初始化时间格式化器
        let dateFormatter = NSDateFormatter()
        //选择地理位置
        dateFormatter.locale = NSLocale(localeIdentifier: "en")
        // 指定格式字符串   Sun Nov 22 11:25:56 +0800 2015
        dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        let createDate = dateFormatter.dateFromString(timeStr)!
        return createDate
    }
    
    //处理时间的方法
    private func dealCreatAtText(createDate: NSDate) -> String?{
        
        //        //获取时间字符串
        //        guard let timeStr = status?.created_at else{
        //
        //            return nil
        //        }
        //        // 2015-08-10 10:10:10 yyyy-MM-dd HH:mm:ss
        //        //转换成NSDate
        //        //初始化时间格式化器
        let dateFormatter = NSDateFormatter()
        //        //选择地理位置
        dateFormatter.locale = NSLocale(localeIdentifier: "en")
        //        // 指定格式字符串   Sun Nov 22 11:25:56 +0800 2015
        //        dateFormatter.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        //        let createDate = dateFormatter.dateFromString(timeStr)!
        
        //        print(timeStr) //Sun Apr 24 22:48:45 +0800 2016
        //        print(createDate) //2016-04-24 14:48:45 +0000
        
        let calendar = NSCalendar.currentCalendar()
        
        // ＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝以下代码供测试使用＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
        //         createDate = NSDate().dateByAddingTimeInterval(-10)
        // ＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝以上代码供测试使用＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
        
        //与当前时间进行对比
        if isDateInThisYear(createDate){
            //            creatAtText = "是今年"
            if calendar.isDateInToday(createDate){
                //是今天
                let currentDate = NSDate()
                //求出当前时间与创建时间的差值(秒)
                let timeInterval = currentDate.timeIntervalSinceDate(createDate)
                if timeInterval < 60{
                    //是否是1分钟之内
                    return "刚刚"
                }else if timeInterval < 3600{
                    //是否1小时之内(xx分钟前)
                    return "\(Int(timeInterval/60))分钟前"
                }else{
                    //xx小时前
                    return "\(Int(timeInterval/3600))小时前"
                }
                
            }else if calendar.isDateInYesterday(createDate){
                //是昨天
                dateFormatter.dateFormat = "昨天 HH:mm"
                return dateFormatter.stringFromDate(createDate)
            }else{
                //其他
                dateFormatter.dateFormat = "MM-dd HH:mm"
                return dateFormatter.stringFromDate(createDate)
            }
            
        }else{
            //            creatAtText = "不是今年"
            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
            return dateFormatter.stringFromDate(createDate)
        }
    }
    
    // 传入一个时间，与当前时间进行对比 ，返回是否是当前时间的年分
    private func isDateInThisYear(date:NSDate) -> Bool{
        
        //当前时间
        let nowDate = NSDate()
        
        let formatter = NSDateFormatter()
        
        formatter.dateFormat = "yyyy"
        
        let nowDateStr = formatter.stringFromDate(nowDate)
        let creDateStr = formatter.stringFromDate(date)
        
        return nowDateStr == creDateStr
    }
    
    //计算单图的大小
    func updateSingleImagePictureSize(){
        
        retweetPicViewSize = calSingleImageSize(status?.retweeted_status?.pic_urls)
        originalPicViewSize = calSingleImageSize(status?.pic_urls)
    }
    
    private func calSingleImageSize(pic_urls: [PictureModel]?) -> CGSize{
        
        //取出图片地址
        guard let imageUrlStr = pic_urls?.first?.thumbnail_pic else{
            
            return CGSizeZero
        }
        
        //1.根据图片的地址,取到已下载好的图片(从缓存里取)
        if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(imageUrlStr){
            
            //返回下载图片的大小
            //获取屏幕的缩放比
            let scale = UIScreen.mainScreen().scale
            
            var size = CGSize(width: image.size.width * scale, height: image.size.height * scale)
            
            //过窄处理(长图)
            if size.width < 50 {
                
                //假定显示出来的图片宽度为100
                let height = 60 * size.height / size.width
                size.width = 60
                size.height = height > 150 ? 150 : height
            }
            
            
            
            return size
        }
        
        return CGSizeZero
    }
    
    //  通过配图的数量 -- 来确定 -- 配图的大小
    private func calRetweetPicViewSize(pic_urls: [PictureModel]?) -> CGSize{
        
        //判断图片的数量
        let count = pic_urls?.count ?? 0
        
        if count == 0{
            
            return CGSizeZero
        }
        
        //计算图片的行数和列数
        let col = count == 4 ? 2 : (count > 3 ? 3 : count)
        let row = ((count -  1) / 3) + 1
        
        //配图的大小
        let margin: CGFloat = 5
        //如果不是单图,每张图片显示的是正方形
        let itemWH = (SCREENW - 2 * StatusCellMargin - 2 * margin) / 3
        
        let picW = CGFloat(col) * itemWH + CGFloat((col - 1)) * margin
        let picH = CGFloat(row) * itemWH + CGFloat((row - 1)) * margin
        
        return CGSize(width: picW, height: picH)
    }
    
    //vip图片的判断逻辑
    private func dealMemberImg(){
        
        guard let rank = status?.user?.mbrank else{
            
            return
        }
        
        if rank > 0 && rank < 7{
            
            memberImage = UIImage(named: "common_icon_membership_level\(rank)")
        }else{
            memberImage = UIImage(named: "common_icon_membership_expired")
        }
        
        if let t = status?.retweeted_status?.text,n = status?.retweeted_status?.user?.name{
            
            retweetText = "@\(n)~\(t)"
        }
        
    }
    
    //来自的文字 截取
    private func dealSource(){
        
        guard let st = status?.source else{
            
            return
        }
        
        //            print(st)
        if let startIndex = st.rangeOfString("\">")?.endIndex,endIndex = st.rangeOfString("</")?.startIndex{
            
            sourceText = "来自 \(st.substringWithRange(startIndex..<endIndex))"
        }
        
    }
    
    //自定义 vip 图片属性 (做逻辑判断 要在 ViewModel中)
    var memberImage: UIImage?
    
    //        {
    //        didSet{
    //            
    //            guard let rank = status?.user?.mbrank else{
    //                
    //                return
    //            }
    //            
    //            if rank > 0 && rank < 7{
    //                
    //                memberImage = UIImage(named: "common_icon_membership_level\(rank)")
    //            }
    //        }
    //    }
    
}
